/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.quangtin3.mb;

import java.io.Serializable;
import java.security.Principal;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.persistence.NoResultException;
import org.quangtin3.entity.User;
import org.quangtin3.sb.UserFacade;

/**
 *
 * @author Quang
 */
@Named(value = "userManager")
@SessionScoped
public class UserManager implements Serializable {

    @EJB
    private UserFacade userFacade;
    private User current;
    private static final Logger LOGGER = Logger.getLogger(UserManager.class.getName());

    /**
     * Creates a new instance of UserManager
     */
    public UserManager() {
    }

    public User getCurrent() {
        if (current == null) {
            Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
            if (principal != null) {
                try {
                    current = userFacade.findByUsername(principal.getName());
                } catch (NoResultException e) {
                    LOGGER.log(Level.SEVERE, "User " + principal.getName() + " not found.", e);
                }
            }
        }
        return current;
    }
}
